import { pageListCustomerAddress, getCustomerAddressById, updateCustomerAddress, deleteCustomerAddress } from '@/services/customer/custom_address_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { PageParams } from '../constants';
import AddForm from './components/AddForm';
import { CustomerAddressVo } from "../constants"
import { set } from 'lodash';



const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<CustomerAddressVo>();
  const [selectedRowsState, setSelectedRows] = useState<CustomerAddressVo[]>([]);
  const [editRow, setEditRow] = useState<CustomerAddressVo>();


  const getCustomerInfo = async (id: string) => {
    try {
      const response = await getCustomerAddressById(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          throw new Error(response.msg);
        }
      }
      setEditRow(response.data);
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };


  const queryPageData = async (pageParams: any) => {
    setLoading(true);
    try {
      const response = await pageListCustomerAddress(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }finally{
      setLoading(false);
    }
  };


  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    // const { current, pageSize, customerCode, customerName, customerStatus } = params
    // let queryParams = {};
    // if (current !== undefined) queryParams.current = current;
    // if (pageSize !== undefined) queryParams.pageSize = pageSize;
    // if (customerCode !== undefined) queryParams.likeCode = customerCode;
    // if (customerName !== undefined) queryParams.likeName = customerName;
    // if (customerStatus !== undefined) queryParams.status = Number(customerStatus);
    return await queryPageData(params);
  }

  const makeActive = (record: CustomerAddressVo) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.customer.address.delete.confirm.title' }),
      content: intl.formatMessage({ id: 'pages.customer.address.delete.confirm.content' }),
      okText: intl.formatMessage({ id: 'pages.button.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.button.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.common.processing' }));
        try {
          const response = await deleteCustomerAddress(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(intl.formatMessage({ id: "request.error.create" }));
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(intl.formatMessage({ id: 'pages.customer.address.delete.success' }));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<CustomerAddressVo>[] = [
    // {
    //   title: (
    //     <FormattedMessage
    //       id="pages.searchTable.serialNumber"
    //       defaultMessage="Number"
    //     />
    //   ),
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 48,
    // },
    {
      title: (
        <FormattedMessage
          id="pages.addForm.customer.customerCode"
          defaultMessage="Customer Code"
        />
      ),
      dataIndex: 'customerCode',
      key: 'customerCode',
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.sn"
          defaultMessage="Code"
        />
      ),
      dataIndex: 'sn',
      key: 'sn',
    },
    {
      title: <FormattedMessage id="pages.cust.address.shipperName" defaultMessage="ShipperName" />,
      dataIndex: 'shipperName',
      key: 'shipperName',
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.country"
          defaultMessage="Country"
        />
      ),
      dataIndex: 'country',
      key: 'country',
      search: false,
      // valueType: 'text',
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.postcode"
          defaultMessage="Postcode"
        />
      ),
      dataIndex: 'postcode',
      key: 'postcode',
      // search: false,
      sorter: true,
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.state"
          defaultMessage="State"
        />
      ),
      dataIndex: 'state',
      key: 'state',
      // search: false,
      sorter: true,
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.city"
          defaultMessage="City"
        />
      ),
      dataIndex: 'city',
      key: 'city',
      // search: false,
      sorter: true,
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.telephone"
          defaultMessage="Telephone"
        />
      ),
      dataIndex: 'telephone',
      key: 'telephone',
      // search: false,
      sorter: true,
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.cust.address.streetAddress"
          defaultMessage="StreetAddress"
        />
      ),
      dataIndex: 'streetAddress1',
      key: 'streetAddress1',
      // search: false,
      sorter: true,
      hideInForm: true
    },
     {
      title: (
        <FormattedMessage
          id="pages.cust.address.company"
          defaultMessage="Company"
        />
      ),
      dataIndex: 'company',
      key: 'company',
      sorter: true,
      search: false,
      hideInForm: true
    },
    {
      title: <FormattedMessage id="pages.operating" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 120,
      disable: true,
      render: (_, record) => [
        <a key="edit" onClick={async () => {
          await getCustomerInfo(record.id);
          // console.log("current:"+JSON.stringify(record));
          setCurrentRow(record);
          handleUpdateModalOpen(true); // 打开编辑弹窗
        }}>
          <FormattedMessage
            id="pages.edit"
            defaultMessage="Edit"
          />
        </a>,
        <a
          key="delete"
          onClick={() => {
            makeActive(record);
            setCurrentRow(record);
          }}
        >
           <FormattedMessage
            id="pages.delete"
            defaultMessage="Delete"
          />
        </a>,

      ],
    },
  ];

  return (
    <PageContainer title={false}>
      <ProTable<CustomerAddressVo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.cust.address.list',
          defaultMessage: 'Shipper Address List',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> {" "}
            <FormattedMessage id="pages.cust.address.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
      // rowSelection={{
      //   onChange: (_, selectedRows) => {
      //     setSelectedRows(selectedRows);
      //   },
      // }}
      />


      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
    </PageContainer>
  );
};

export default TableList;
